﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using Kinlo.MESDocking.MQTT.MQTTMessModels;
using NewLife;
using NewLife.Data;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using UIWindows.Domains;
using UIWindows.GlobalStatics;
using UIWindows.MESModels;
using UIWindows.Models;
using UIWindows.Models.Devices;
using UIWindows.Models.MES;
using UIWindows.Models.ParameterModels;
using UIWindows.Tools.Helper;
using UIWindows.Views;
using UIWindows.Views.DeviceInteractiveaddressItems;
using UIWindows.Views.MesParameterItems;
using XCode;
using XingLucifer.Devices;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models;
using static log4net.Appender.RollingFileAppender;

namespace UIWindows.Services
{
    public abstract class HelperBase
    {
        public ObservableCollection<BaseParameteModel> _baseParamete { get; set; }
        public ObservableCollection<CollectParameterModel> _collectParamete { get; set; } = null;
        public DeviceClientModel _deviceModel { get; set; }
        public ParameterStatic _parameterStatic { get; set; }
        public DeviceInteractiveaddressStatic _deviceInteractiveaddressStatic { get; set; }

        protected DeviceConfigStatic _deviceConfig { get; set; }
        protected HomeStatic _homeStatic { get; set; }
        public TemporaryStatic _temporaryStatic { get; set; }
        public Action<string, string, string, string, string, long, DateTime, string, string, string, string> _log { get; set; }

        public MESCollectionItemsParameterModel _parameter { get; set; }
        public Action<string, string, string> _dialog { get; set; }

        public SnowflakeManager _snowflake;
        
       public SystemConfigStatic _systemConfig { get; set; }
        /// <summary>
        /// 白班NG分类地址
        /// </summary>
        public ObservableCollection<MesRunParameterModel> _mesRunParameters1 { get; set; } = null;
        /// <summary>
        /// 夜班NG分类地址
        /// </summary>
        public ObservableCollection<MesRunParameterModel> _mesRunParameters2 { get; set; } = null;

        public MachineInfoTypes machineInfo_Type;

        public DateTime startTime { get; set; }
        MESGeneralData mesGeneralData { get; set; }
        public HelperBase(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
             DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
            HomeStatic homeStatic,
            Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog)
        {
            try
            {
               
                _deviceInteractiveaddressStatic = deviceInteractiveaddressStatic;
                _deviceModel = deviceModel;
                _temporaryStatic = temporaryStatic;
                _parameterStatic = parameterStatic;
                _deviceConfig = deviceConfigStatic;
                _homeStatic = homeStatic;
                startTime = DateTime.Now;

                var machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), deviceModel.ServiceName);
                machineInfo_Type= machineInfoType;
                if (_deviceInteractiveaddressStatic.BaseParameters != null && _deviceInteractiveaddressStatic.BaseParameters.ContainsKey(machineInfoType))
                {
                    _baseParamete = _deviceInteractiveaddressStatic.BaseParameters[machineInfoType];
                }


                if (_deviceInteractiveaddressStatic.CollectParameters != null && _deviceInteractiveaddressStatic.CollectParameters.ContainsKey(machineInfoType))
                {
                    _collectParamete = _deviceInteractiveaddressStatic.CollectParameters[machineInfoType];
                }

                if (_parameterStatic.MESCollectionItemsParameter != null && _parameterStatic.MESCollectionItemsParameter.ContainsKey(machineInfoType))
                {
                    _parameter = _parameterStatic.MESCollectionItemsParameter[machineInfoType];
                }

                if(deviceInteractiveaddressStatic.MesRunParameters!=null&& deviceInteractiveaddressStatic.MesRunParameters.ContainsKey((machineInfoType,ShiftTypes.白班)))
                {
                    _mesRunParameters1 = deviceInteractiveaddressStatic.MesRunParameters[(machineInfoType, ShiftTypes.白班)];

                    _mesRunParameters2 = deviceInteractiveaddressStatic.MesRunParameters[(machineInfoType, ShiftTypes.夜班)];
                }

                _systemConfig = systemConfigStatic;
                _log = log;
                _dialog = dialog;
                mesGeneralData = new MESGeneralData(_log, _dialog, machineInfo_Type);
                _snowflake = new SnowflakeManager(12);
            }catch(Exception ex)
            {
                Console.WriteLine();
            }
            
        }
        protected void RunLog(string info, MessageLevelType levelType = MessageLevelType.信息)
        {
            if (_deviceModel == null)
            {
                return;
            }
            $"[{_deviceModel.ServiceName}]-[{_deviceModel.TaskType}]-[{_deviceModel.DeviceType}]：{info}".RunLog(levelType);
        }

        public virtual Task Handle()
        {
            return Task.CompletedTask;
        }
        //str = str.Trim('\"');
        public BaseParameteModel GetAddReassData(string Name)
        {
            var model = _baseParamete.FirstOrDefault(x => x.Name.Contains(Name));
            //if (model != null)
            //{
            //    model.PLCAddress = model.PLCAddress.Trim('\"');
            //}
            return model;
        }

        public T CreateEntityType<T>() where T : class
        {
            MachineInfoTypes machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), _deviceModel.ServiceName);
            switch (machineInfoType)
            {
                case MachineInfoTypes.卷芯上料:
                    return CreateData(new CoilCoreLoadingData()) as T;
                case MachineInfoTypes.换套杯:
                    return CreateData(new CupSleeveChangingData()) as T;
                case MachineInfoTypes.折极耳:
                    return CreateData(new PoleEarFoldingData()) as T;

                case MachineInfoTypes.面垫机:
                    return CreateData(new FaceCushionData()) as T;
                case MachineInfoTypes.入壳机:
                    return CreateData(new ShellInsertionData()) as T;
                case MachineInfoTypes.点底焊:
                    return CreateData(new SpotoWeldData()) as T;
                case MachineInfoTypes.辊槽机:
                    return CreateData(new GrooveRollingMachineData()) as T;
                case MachineInfoTypes.短路测试仪:
                    return CreateData(new ShortCircuitTesterData()) as T;
                case MachineInfoTypes.左装盘机:
                    return CreateData(new TrayFillerLeftData()) as T;
                case MachineInfoTypes.右装盘机:
                    return CreateData(new TrayFillerRightData()) as T;

                case MachineInfoTypes.左拆盘机:
                    return CreateData(new DismantlingDiscLeftData()) as T;
                case MachineInfoTypes.右拆盘机:
                    return CreateData(new DismantlingDiscRightData()) as T;
                case MachineInfoTypes.盖帽焊:
                    return CreateData(new CapWeldingData()) as T;
                case MachineInfoTypes.封口机:
                    return CreateData(new SealingMachineData()) as T;

                case MachineInfoTypes.清洗机:
                    return CreateData(new CleaningData()) as T;
                case MachineInfoTypes.套膜机:
                    return CreateData(new MantleData()) as T;
                case MachineInfoTypes.喷码机:
                    return CreateData(new MarkingData()) as T;
                case MachineInfoTypes.预充装盘:
                    return CreateData(new Plate()) as T;

                default:
                    return null;
            }
           
        }

        private dynamic CreateData(dynamic data)
        {
            data.Id = _snowflake.NextId();
            DateTime dateTime = DateTime.Now;
            data.AcquisitionTime = dateTime;
            data.EquipmentStatus = _parameter.MachineStatus;
            data.EquipmentCode = _parameter.EquipmentCode;
            data.Operator = _parameter.UserName;
            data.Team = _parameter.ClassTeam;
            data.Shift = _parameter.Class;
            data.WorkOrderNo = _parameter.WorkOrder;
            data.EquipmentCode= _parameter.EquipmentCode;
            data.WorkOrderNo = _parameter.WorkOrder;
            data.ProcessId = _parameter.process_id;
            data.MaterialCode = _parameter.Material_Code;
            data.PcNo = _parameter.BatchNo;
            data.WorkorderstatusName = _parameter.WorkOrderStatus_Name;
            //data.PlanedStart = DateTime.Parse(_parameter.PlanedStart).GetJSTimeUtc();
            //data.PlanedEndDate = DateTime.Parse(_parameter.PlanedEndDate).GetJSTimeUtc();
            data.PlanedStart = _parameter.PlanedStart;
            data.PlanedEndDate = _parameter.PlanedEndDate;
            data.PutIntoNumber = _parameter.PutIntoNumber.ToString();
            data.QualifiedNumber = _parameter.QualifiedNumber.ToString();
            data.UnqualifiedNumber = _parameter.UnqualifiedNumber.ToString();

            if(machineInfo_Type==MachineInfoTypes.喷码机)
            {
                //喷码工位号，18线固定传4，26线传3
                data.PengmaParameters1 = "4";
            }
            if(machineInfo_Type==MachineInfoTypes.左拆盘机)
            {
                //喷码工位号，18线固定传4，26线传3
                data.Position = 0;
            }
            if(machineInfo_Type==MachineInfoTypes.右拆盘机)
            {
                //喷码工位号，18线固定传4，26线传3
                data.Position = 1;
            }
            return data;
        }

        public (Type, Type) GetEntityType()
        {
            Type resultType = null;
            Type resultMetaType = null;
            MachineInfoTypes machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), _deviceModel.ServiceName);
            switch (machineInfoType)
            {
                case MachineInfoTypes.卷芯上料:
                    resultType = typeof(CoilCoreLoadingData);
                    resultMetaType = typeof(CoilCoreLoadingData.Meta);
                    break;
                case MachineInfoTypes.换套杯:
                    resultType = typeof(CupSleeveChangingData);
                    resultMetaType = typeof(CupSleeveChangingData.Meta);
                    break;
                case MachineInfoTypes.折极耳:
                    resultType = typeof(PoleEarFoldingData);
                    resultMetaType = typeof(PoleEarFoldingData.Meta);
                    break;
                case MachineInfoTypes.入壳机:
                    resultType = typeof(ShellInsertionData);
                    resultMetaType = typeof(ShellInsertionData.Meta);
                    break;
                case MachineInfoTypes.点底焊:
                    resultType = typeof(SpotoWeldData);
                    resultMetaType = typeof(SpotoWeldData.Meta);
                    break;
                case MachineInfoTypes.辊槽机:
                    resultType = typeof(GrooveRollingMachineData);
                    resultMetaType = typeof(GrooveRollingMachineData.Meta);
                    break;
                case MachineInfoTypes.短路测试仪:
                    resultType = typeof(ShortCircuitTesterData);
                    resultMetaType = typeof(ShortCircuitTesterData.Meta);
                    break;
                case MachineInfoTypes.面垫机:
                    resultType = typeof(FaceCushionData);
                    resultMetaType = typeof(FaceCushionData.Meta);
                    break;
                case MachineInfoTypes.左装盘机:
                    resultType = typeof(TrayFillerLeftData);
                    resultMetaType = typeof(TrayFillerLeftData.Meta);
                    break;
                case MachineInfoTypes.右装盘机:
                    resultType = typeof(TrayFillerRightData);
                    resultMetaType = typeof(TrayFillerRightData.Meta);
                    break;
                case MachineInfoTypes.左拆盘机:
                    resultType = typeof(DismantlingDiscLeftData);
                    resultMetaType = typeof(DismantlingDiscLeftData.Meta);
                    break;
                case MachineInfoTypes.右拆盘机:
                    resultType = typeof(DismantlingDiscRightData);
                    resultMetaType = typeof(DismantlingDiscRightData.Meta);
                    break;
                case MachineInfoTypes.盖帽焊:
                    resultType = typeof(CapWeldingData);
                    resultMetaType = typeof(CapWeldingData.Meta);
                    break;
                case MachineInfoTypes.封口机:
                    resultType = typeof(SealingMachineData);
                    resultMetaType = typeof(SealingMachineData.Meta);
                    break;
                case MachineInfoTypes.清洗机:
                    resultType = typeof(CleaningData);
                    resultMetaType = typeof(CleaningData.Meta);
                    break;
                case MachineInfoTypes.套膜机:
                    resultType = typeof(MantleData);
                    resultMetaType = typeof(MantleData.Meta);
                    break;
                case MachineInfoTypes.喷码机:
                    resultType = typeof(MarkingData);
                    resultMetaType = typeof(MarkingData.Meta);
                    break;
                case MachineInfoTypes.预充装盘:
                    resultType = typeof(Plate);
                    resultMetaType = typeof(Plate.Meta);
                    break;

                default:
                    return (null,null);
            }

        
            return (resultType, resultMetaType);
        }

        public string ProcessList(List<ushort> values, int num)
        {
            double result;
            
            ushort firstValue = 0;
            ushort secondValue = 0;

            if (values.Count < 2 || secondValue == 0)
            {
                firstValue = values[0];
                result = firstValue;
                //return (values[0] / 1000.0).ToString("0.000");
            }
            else
            {
                firstValue = values[0];
                secondValue = values[1];
                // 如果第二个值不为零，将两个值转换成字符串后处理
                string stringValue = $"{firstValue}{secondValue:D3}"; // 使用:D3格式化为3位数，不足3位自动用零填充
                result = double.Parse(stringValue); // 将值转换为保留后三位小数的形式
                //result = double.Parse(stringValue) / 1000.0; // 将值转换为保留后三位小数的形式
            }
            return num switch
            {
                0 => result.ToString(),
                1 => (result / 10.0).ToString(),
                2 => (result / 100.0).ToString("0.00"),
                3 => (result / 1000.0).ToString("0.000"),
                _ => result.ToString()
            };

            //return result.ToString("0.000"); // 将结果转换为保留后三位小数的字符串形式
        }


        public string ProcessUint(uint values, int num)
        {

            return num switch
            {
                0 or 1 => values.ToString(),
                2 => (values / 100.0).ToString("0.00"),
                3 => (values / 1000.0).ToString("0.000"),
                _ => values.ToString()
            };

            //return result.ToString("0.000"); // 将结果转换为保留后三位小数的字符串形式
        }
        public string Processint(int values, int num)
        {

            return num switch
            {
                0 or 1 => values.ToString(),
                2 => (values / 100.0).ToString("0.00"),
                3 => (values / 1000.0).ToString("0.000"),
                _ => values.ToString()
            };

            //return result.ToString("0.000"); // 将结果转换为保留后三位小数的字符串形式
        }
        /// <summary>
        /// 扫码枪通用扫码方法
        /// </summary>
        /// <param name="scancode_count">重复扫码次数</param>
        /// <param name="devices">扫码枪设备</param>
        /// <param name="index">设备序号</param>
        /// <param name="barcodeNumber">条码数量</param>
        /// <param name="barcode_length">扫码枪返回的长度</param>
        /// <param name="isBattery">是否是电池码， true 是  false 否（托盘扫码）</param>
        /// <returns></returns>
        public string ScanCode(int scancode_count, IDevices devices, int index, bool isBattery = true, int barcodeNumber = 1, int barcode_length = 1024)
        {
            List<string> barcodeList = new List<string>();
            for (int i = 0; i <= scancode_count; i++)
            {
                barcodeList.Clear();
                string? barcode = devices.ReadSingle<string>(0, barcode_length);
                RunLog($"-[{index}] 扫码枪返回：{barcode}");
                if (barcodeNumber > 1)
                {
                    string[] barcodes = barcode.Split(',');
                    if (barcodes.Length < barcodeNumber)
                    {
                        barcodeList = Enumerable.Repeat("ERROR", barcodeNumber).ToList();
                        RunLog($"-[{index}] 扫码枪{barcode}条码个数和需要个数{barcodeNumber}不符");
                    }
                    else
                    {
                        for (int k = 0; k < barcodeNumber; k++)
                        {
                            string barcode1 = System.Text.RegularExpressions.Regex.Match(barcodes[k], isBattery ? _systemConfig.SCM.BarcodeRules : _systemConfig.SCM.CupCodeRules, System.Text.RegularExpressions.RegexOptions.Compiled).Value;
                            RunLog($"-[{index}] 位置:[{k + 1}] 校验后:[{barcode1}]");
                            barcodeList.Add($"{(string.IsNullOrEmpty(barcode1) ? "ERROR" : barcode1)}");
                        }
                    }
                }
                else
                {
                    string barcode1 = System.Text.RegularExpressions.Regex.Match(barcode, isBattery ? _systemConfig.SCM.BarcodeRules : _systemConfig.SCM.CupCodeRules, System.Text.RegularExpressions.RegexOptions.Compiled).Value;
                    RunLog($"-[{index}] 校验后:[{barcode1}]");
                    barcodeList.Add($"{(string.IsNullOrEmpty(barcode1) ? "ERROR" : barcode1)}");
                }
                if (!barcodeList.Any(x => x == "ERROR")) break;
                Thread.Sleep(_parameterStatic.RunParameter.IntervalTime_ScanCode);
            }
            string resutBarcode = barcodeList.Join("_");
            return resutBarcode;
        }

        /// <summary>
        /// 标准工艺参数获取更新保存方法
        /// </summary>
        public void PumDataSave()
        {
            try
            {

                Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    };
                var mesParameters = new Dictionary<string, object>()
                        {
                            {"EquipmentCode", _parameter.EquipmentCode },     //设备编码
                            {"WorkOrderId",_parameter.WorkOrder },             //工单
                        };


                mesParam.Add("parameter", mesParameters);

                var result = mesGeneralData.MESInteraction(_parameterStatic.MESParameter.GeneralDataRoute,
                     _parameterStatic.MESParameter.GeneralDataTime,
                     1, DateTime.Now, mesParam);
                if(mesParam.ContainsKey("result"))
                {
                    string resultData = mesParam["result"]?.ToString();
                    if (!string.IsNullOrWhiteSpace(resultData))
                    {
                        try
                        {
                            var generalData = JsonConvert.DeserializeObject<List<MESGeneralDataReturnModel>>(resultData);
                            generalData = generalData == null ? new List<MESGeneralDataReturnModel>() : generalData;

                            _parameter.GeneralData = new List<MESGeneralDataReturnModel>(generalData);

                            // 继续你的代码
                        }
                        catch (JsonReaderException ex)
                        {
                            Console.WriteLine("标准工艺参数获取解析JSON时出错: " + ex.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("标准工艺参数结果字符串为空或无效");
                    }
                }
              

             
            }
            catch (Exception ex)
            {
                RunLog($" 标准工艺参数获取更新保存：{ex}");
            }
            finally
            {

            }
        }


        /// <summary>
        /// 卷芯上料扫码上传MES接口
        /// </summary>
        public void MESWinderInRecordUpload(IMESInteraction _interaction, string barcode)
        {

            Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    };

            Dictionary<string, object> mesParameters = new Dictionary<string, object>
                        {
                            { "Team", _parameter.ClassTeam },
                            { "Shift", _parameter.Class },
                            { "Operator", _parameter.UserName },
                            { "EquipmentCode", _parameter.EquipmentCode },
                            { "WorkOrderNo", _parameter.WorkOrder },
                            { "PalletNo", barcode },
                            { "LoadInboundTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                            { "NumPerPallet", "256" },
                        };
            mesParam.Add("parameter", mesParameters);

            var result = _interaction.MESInteraction(_parameterStatic.MESParameter.WinderInRecordRouter,
                 _parameterStatic.MESParameter.WinderInRecordTime,
                 1, DateTime.Now, mesParam);
        }
        /// <summary>
        /// 装盘机出站接口
        /// </summary>
        /// <param name="_interaction"></param>
        /// <param name="barcode"></param>
        public void MESWinderOutRecordAddRecUpload(IMESInteraction _interaction, string barcode)
        {

            Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    };


            Dictionary<string, object> mesParameters = new Dictionary<string, object>
                        {
                            { "Team", _parameter.ClassTeam },
                            { "Shift", _parameter.Class },
                            { "Operator", _parameter.UserName },
                            { "EquipmentCode", _parameter.EquipmentCode },
                            { "WorkOrderNo", _parameter.WorkOrder },
                            { "PalletNo", barcode },
                            { "LoadStartTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                            { "LoadEndTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                            { "NumPerPallet", "240" },
                        };

            mesParam.Add("parameter", mesParameters);

            var result = _interaction.MESInteraction(_parameterStatic.MESParameter.WinderOutRecordRouter,
                 _parameterStatic.MESParameter.WinderOutRecordTime,
                 1, DateTime.Now, mesParam);
        }
        /// <summary>
        /// 拆盘机出站 注液上料(拆盘)扫描记录接口
        /// </summary>
        /// <param name="_interaction"></param>
        /// <param name="barcode"></param>
        public void MESTrayScanRecord(IMESInteraction _interaction,List<ParentVO> trayScanRecordList)
        {

            Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    };

            trayScanRecordList.ForEach(trayScanRecord =>
            {
                trayScanRecord.Workorder = _parameter.WorkOrder;
                trayScanRecord.MaterialCode = _parameter.Material_Code;
                trayScanRecord.MaterialSpec = _parameter.Material_Spec;
                trayScanRecord.Process = _parameter.process_id;
                trayScanRecord.EquipmentCode = _parameter.EquipmentCode;
                trayScanRecord.Operator = _parameter.UserName;
                trayScanRecord.Batchnumber = _parameter.BatchNo;
            });
            RootObject rootObject = new RootObject
            {
                parentvo = trayScanRecordList
            };

            mesParam.Add("parameter", rootObject);

            var result = _interaction.MESInteraction(_parameterStatic.MESParameter.OeeWarningRouter,
                 _parameterStatic.MESParameter.OeeWarningTime,
                 1, DateTime.Now, mesParam);
        }

        /// <summary>
        /// 点底焊机解析数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public SpotWelderData ParseSpotWelderData(string data)
        {
              StringBuilder _receivedData = new StringBuilder();
             SpotWelderData parsedData = null;

            if (data.Length > 0 && data.Contains("\r"))
            {
                _receivedData.Append(data);
                // 找到结束符的位置
                int endIndex = data.IndexOf("\r");

                // 截取结束符之前的数据
                string completeData = _receivedData.ToString(0, _receivedData.Length - (data.Length - endIndex));

                if (!string.IsNullOrWhiteSpace(completeData))
                {
                    // 查找"W2"的位置
                    int startIndex = completeData.LastIndexOf("W2");
                    if (startIndex != -1)
                    {
                        // 保留"W2"之后的所有字符
                        string remainingData = completeData.Substring(startIndex + 3);

                        // 分割字符串以逗号为分隔符
                        string[] values = remainingData.Split(',');

                        // 检查是否有足够的数值
                        if (values.Length >= 6)
                        {
                            string currentPeakValue = values[0].Trim();
                            string currentAverageValue = values[1].Trim();
                            string voltagePeakValue = values[2].Trim();
                            string voltageAverageValue = values[3].Trim();
                            string powerValue = values[4].Trim();
                            string resistanceValue = values[5].Trim();

                            // 打印解析出的数值
                            //Console.WriteLine("电流值峰值: " + currentPeakValue);
                            //Console.WriteLine("电流值平均值: " + currentAverageValue);
                            //Console.WriteLine("电压值峰值: " + voltagePeakValue);
                            //Console.WriteLine("电压值平均值: " + voltageAverageValue);
                            //Console.WriteLine("功率值: " + powerValue);
                            //Console.WriteLine("电阻值: " + resistanceValue);

                            // 创建并设置解析后的数据对象
                            parsedData = new SpotWelderData
                            {
                                VoltagePeak = voltagePeakValue,
                                VoltageAverage = voltageAverageValue,
                                CurrentPeak = currentPeakValue,
                                CurrentAverage = currentAverageValue,
                                Power = powerValue,
                                Impedance = resistanceValue
                            };
                        }
                        else
                        {
                            Console.WriteLine("解析出的数值不完整");
                        }
                    }
                    else
                    {
                        Console.WriteLine("未找到\"W2\"标识");
                    }
                }

                // 清空已接收的数据缓冲区
                _receivedData.Clear();
            }

            return parsedData;
        }

        /// <summary>
        /// 切换班组班次 OR 切换工单调用
        /// </summary>
        public void MESCountUpLoad_Hour(string message)
        {
            //if (SystemConfig.SCM.IsShowWarnTip != false || SystemConfig.SCM.PerformTaskName?.Content.ToString() == "    运  行    ")
            //{
            //    _ = "请先点击运行，运行成功后，才能切换班组班次".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
            //    return;
            //}

            //var plcDataList = DeviceConfig.DeviceList.Where(x => x.DeviceType == DeviceTypes.KVPLC).ToList();

            var mesData_HourInteraction = new MESProductCountData_Hour(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog, machineInfo_Type);

            var mesData_DayInteraction = new MESProductCountData_Day(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog, machineInfo_Type);


            var _parameter = _parameterStatic.MESCollectionItemsParameter[machineInfo_Type];

            $"{machineInfo_Type.ToString()}{message}产量投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
           if(_parameter.PutIntoNumber==0&& _parameter.QualifiedNumber == 0&& _parameter.UnqualifiedNumber == 0)
            {
                $"{machineInfo_Type.ToString()}{message}当前产量OKNG均为0，{message}不调用生产统计接口".RunLog(MessageLevelType.警告);
            }

            try
            {
                Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                               new Dictionary<string, object>()
                                               {
                                                    { "Team", _parameter.ClassTeam },
                                                    { "Shift", _parameter.Class },
                                                    { "WorkNumber", _parameter.UserName },
                                                    { "EquipmentNo", _parameter.EquipmentCode },
                                                    { "WorkOrderNo", _parameter.WorkOrder },
                                                    { "PutIntoNumber", _parameter.PutIntoNumber },
                                                    { "QualifiedNumber", _parameter.QualifiedNumber },
                                                    { "UnqualifiedNumber", _parameter.UnqualifiedNumber },
                                                    { "ProductionStartTime", DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss") },
                                                    { "ProductionEndTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                                                }
                                        }
                                    }
                                };
                Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                    { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };



                var result = mesData_HourInteraction.MESInteraction(_parameterStatic.MESParameter.ProductCountDataRouter,
                     _parameterStatic.MESParameter.ProductCountDataTime,
                     1, DateTime.Now, mesParams);

                $"{machineInfo_Type.ToString()}【{message}生产统计小时上传MES{result.ToString()}投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
            }
            catch (Exception ex)
            {
                $"{machineInfo_Type.ToString()}{message}生产统计小时小时小时上传MES错误：{ex}".RunLog(MessageLevelType.错误);
            }

            try
            {


                Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                            new Dictionary<string, object>(){
                                            { "Team", _parameter.ClassTeam },
                                            { "Shift", _parameter.Class },
                                            { "WorkNumber", _parameter.UserName },
                                            { "EquipmentNo", _parameter.EquipmentCode },
                                            { "WorkOrderNo", _parameter.WorkOrder },
                                            { "PutIntoNumber", _parameter.PutIntoNumber },
                                            { "QualifiedNumber", _parameter.QualifiedNumber },
                                            { "UnqualifiedNumber", _parameter.UnqualifiedNumber },
                                            }
                                        }

                                   },
                                };

                Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                  { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };

                var result = mesData_DayInteraction.MESInteraction(_parameterStatic.MESParameter.ProductCountData_DayRouter,
                     _parameterStatic.MESParameter.ProductCountData_DayTime,
                     1, DateTime.Now, mesParams);

                $"{machineInfo_Type.ToString()}{message}生产统计天天上传MES{result.ToString()}投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
            }
            catch (Exception ex)
            {
                $"{machineInfo_Type.ToString()}{message}生产统计天天天天上传MES错误：{ex}".RunLog(MessageLevelType.错误);
            }

            var CountAddressData=GetAddReassData("MachineInCountAddress");
            var OkCountAddressData = GetAddReassData("MachineOkCountAddress");
            var NgCountAddressData = GetAddReassData("MachineNgCountAddress");

            var isCount1 = _deviceModel.PLC.Write<short>(CountAddressData.PLCAddress, new short[] { 0 });
            var isCount2 = _deviceModel.PLC.Write<short>(IncrementStringNumber(CountAddressData.PLCAddress), new short[] { 0 });
            var isOkCount1 = _deviceModel.PLC.Write<short>(OkCountAddressData.PLCAddress, new short[] { 0 });
            var isOkCount2 = _deviceModel.PLC.Write<short>(IncrementStringNumber(OkCountAddressData.PLCAddress), new short[] { 0 });
            var isNgCount1 = _deviceModel.PLC.Write<short>(NgCountAddressData.PLCAddress, new short[] { 0 });
            var isNgCount2 = _deviceModel.PLC.Write<short>(IncrementStringNumber(NgCountAddressData.PLCAddress), new short[] { 0 });

            $"{machineInfo_Type}【切换工单班组班次】产量清零结果信息{isCount1} {isCount2} {isOkCount1} {isOkCount2} {isNgCount1} {isNgCount2}".RunLog(MessageLevelType.信息);
            _parameter.PutIntoNumber = 0;
            _parameter.QualifiedNumber = 0;
            _parameter.UnqualifiedNumber = 0;
            _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].PutIntoNumber = 0;
            _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].QualifiedNumber = 0;
            _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].UnqualifiedNumber = 0;


        }



        /// <summary>
        /// 切换班组班次 OR 切换工单调用 上传工艺参数
        /// </summary>
        public void Upload_Parameters(ObservableCollection<MesOutputParameterModel> _mesParameter, MESProcessParameter _mesProcessParameter)
        {
            object list = null;
            XCode.Configuration.Field fd = null;
            try
            {
                switch (machineInfo_Type)
                {
                    case MachineInfoTypes.卷芯上料:
                        fd = CoilCoreLoadingData.Meta.Table.FindByName(CoilCoreLoadingData.__.AcquisitionTime);
                        list = CoilCoreLoadingData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.换套杯:
                        fd = CupSleeveChangingData.Meta.Table.FindByName(CupSleeveChangingData.__.AcquisitionTime);
                        list = CupSleeveChangingData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.折极耳:
                        fd = PoleEarFoldingData.Meta.Table.FindByName(PoleEarFoldingData.__.AcquisitionTime);
                        list = PoleEarFoldingData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.入壳机:
                        fd = ShellInsertionData.Meta.Table.FindByName(ShellInsertionData.__.AcquisitionTime);
                        list = ShellInsertionData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.点底焊:
                        fd = SpotoWeldData.Meta.Table.FindByName(SpotoWeldData.__.AcquisitionTime);
                        list = SpotoWeldData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.辊槽机:
                        fd = GrooveRollingMachineData.Meta.Table.FindByName(GrooveRollingMachineData.__.AcquisitionTime);
                        list = GrooveRollingMachineData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.短路测试仪:
                        fd = ShortCircuitTesterData.Meta.Table.FindByName(ShortCircuitTesterData.__.AcquisitionTime);
                        list = ShortCircuitTesterData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    case MachineInfoTypes.面垫机:
                        fd = FaceCushionData.Meta.Table.FindByName(FaceCushionData.__.AcquisitionTime);
                        list = FaceCushionData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.左装盘机:
                        fd = TrayFillerLeftData.Meta.Table.FindByName(TrayFillerLeftData.__.AcquisitionTime);
                        list = TrayFillerLeftData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.右装盘机:
                        fd = TrayFillerRightData.Meta.Table.FindByName(TrayFillerRightData.__.AcquisitionTime);
                        list = TrayFillerRightData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.左拆盘机:
                        fd = DismantlingDiscLeftData.Meta.Table.FindByName(DismantlingDiscLeftData.__.AcquisitionTime);
                        list = DismantlingDiscLeftData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.右拆盘机:
                        fd = DismantlingDiscRightData.Meta.Table.FindByName(DismantlingDiscRightData.__.AcquisitionTime);
                        list = DismantlingDiscRightData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;

                    case MachineInfoTypes.盖帽焊:
                        fd = CapWeldingData.Meta.Table.FindByName(CapWeldingData.__.AcquisitionTime);
                        list = CapWeldingData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;

                    case MachineInfoTypes.封口机:
                        fd = SealingMachineData.Meta.Table.FindByName(SealingMachineData.__.AcquisitionTime);
                        list = SealingMachineData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;

                    case MachineInfoTypes.清洗机:
                        fd = CleaningData.Meta.Table.FindByName(CleaningData.__.AcquisitionTime);
                        list = CleaningData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.套膜机:
                        fd = MantleData.Meta.Table.FindByName(MantleData.__.AcquisitionTime);
                        list = MantleData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.喷码机:
                        fd = MarkingData.Meta.Table.FindByName(MarkingData.__.AcquisitionTime);
                        list = MarkingData.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];

                        break;
                    case MachineInfoTypes.预充装盘:
                        fd = Plate.Meta.Table.FindByName(Plate.__.AcquisitionTime);
                        list = Plate.FindAll(null, fd.Desc(), null, 0, 1).ToList()[0];
                        break;
                    default: break;
                }
            }
            catch { }
            

            if (list != null && _mesParameter != null)
            {

                Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    };
                var mesParameters = new Dictionary<string, object>();



                //// var propertyInfos = production.GetType().GetProperties();
                //var produceInEntityList = new List<Dictionary<string, object>>();
                foreach (var item in _mesParameter)
                {

                    if (item.IsEnable)
                    {
                        try
                        {
                            var valueType = GetTypeByStringHelper.GetTypeByString(item.DataType);
                            if (item.Description == null || string.IsNullOrEmpty(item.Description) ||
                                item.PropertyName == null || string.IsNullOrEmpty(item.PropertyName))
                            {
                                //找不到这个电池的参数
                            }
                            else
                            {
                                var propertyInfo = list.GetType().GetProperty(item.PropertyName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                                //var ret = propertyInfos.Where(x => x.Name == item.PropertyName).FirstOrDefault();                       
                                if (propertyInfo != null) //如果电池中有此参数
                                {
                                    //取出值
                                    var value = propertyInfo.GetValue(list, null);
                                    if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                                    {
                                        value = "0";
                                    }
                                    if (item.DataType == "DateTime")
                                    {
                                        string inputFormat = "yyyy/MM/dd HH:mm:ss"; // 输入的格式
                                        string outputFormat = "yyyy-MM-dd HH:mm:ss"; // 输出的格式

                                        DateTime dateTime;
                                        if (DateTime.TryParseExact(value.ToString(), inputFormat, null, System.Globalization.DateTimeStyles.None, out dateTime))
                                        {
                                            value = dateTime.ToString(outputFormat);
                                        }
                                    }
                                    mesParameters.TryAdd(item.TechnicsParamCode, value);
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }


                    }
                    //parameter.TryAdd("produceParamEntityList", produceInEntityList);
                }



                mesParam.Add("parameter", mesParameters);

                var result = _mesProcessParameter.MESInteraction(_parameterStatic.MESParameter.EquipUploadParamRoute,
                     _parameterStatic.MESParameter.EquipUploadParamTime,
                     1, DateTime.Now, mesParam);

                RunLog($"更换工号或者工单 调用工艺参数接口结果：{result.ToString()}");
            }
        }


        public string IncrementStringNumber(string str)
        {
            string prefix = str.Substring(0, 2); // 获取前缀"DM"
            string number = str.Substring(2); // 获取数字部分"50080"
            uint num = UInt32.Parse(number); // 将数字部分转换为uint
            num++; // 数字部分加1
            return prefix + num.ToString(); // 将新的数字部分和前缀拼接起来
        }

        #region 采集工艺参数
        public void ProcessParameters(object entity, PLCBase InjMachine)
        {
            if(_collectParamete!=null&& _collectParamete.Count>0)
            {
                foreach (var item in _collectParamete)
                {
                    var valueType = GetTypeByStringHelper.GetTypeByString(item.DataType);
                    var sss = entity.GetType();
                    var entityInfo = entity.GetType().GetProperty(item.PropertyName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    if (entityInfo != null)
                    {
                        try
                        {
                            string value = "0";
                            if (item.IsEnable)
                            {
                                if (item.IsCCDResult)
                                {
                                    value = ProcessList(InjMachine.Read(item.PLCAddress, item.PLCAddressLength), 0);

                                    value= value switch
                                    {
                                        "10" => "1",
                                        "20" => "2",
                                        _ => value
                                    };
                                }
                                else
                                {
                                    //if (item.DataType.Contains("uint32"))
                                    //{
                                    //    var valueData = InjMachine.ReadUInt32(item.PLCAddress, 1);
                                    //    value = ProcessUint(valueData[0], item.DecimalNum).ToString();
                                    //}
                                    if (item.DataType.Contains("int32"))
                                    {
                                        var valueData = InjMachine.ReadUInt32(item.PLCAddress, 1);
                                        value = ProcessUint(valueData[0], item.DecimalNum).ToString();
                                    }
                                    else
                                    {
                                        value = ProcessList(InjMachine.Read(item.PLCAddress, item.PLCAddressLength), item.DecimalNum);
                                    }
                                }
                            }
                            //赋值
                            entityInfo.SetValue(entity, Convert.ChangeType(value, entityInfo.PropertyType), null);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
            }
           
        }
        #endregion

        #region 读取焊机数据
        public void ProcessSpotWelderData(object entity)
        {
            if (machineInfo_Type == MachineInfoTypes.点底焊)
            {
                var spotWelderDevice = _deviceConfig.DeviceList.Where(x => x.ServiceName == _deviceModel.ServiceName
          && x.TaskType == TaskTypes.点底焊机).OrderBy(x=>x.Index).ToList();
                if (spotWelderDevice != null && spotWelderDevice.Count > 0)
                {
                    var spotWelderDataList = new List<SpotWelderData>();
                    foreach (var item in spotWelderDevice)
                    {
                        var spotWelderDatas = item.Communication.Read();
                        if (spotWelderDatas != null)
                        {
                            var data = ParseSpotWelderData(spotWelderDatas); //解析数据
                            if (data != null)
                            {
                                spotWelderDataList.Add(data);
                            }
                        }
                    }

                    var parameters = new Dictionary<string, string>
                        {
                            { "DiandiParameters9", spotWelderDataList.Count > 0 ? spotWelderDataList[0]?.VoltagePeak ?? "0" : "0" },
                            { "DiandiParameters10", spotWelderDataList.Count > 0 ? spotWelderDataList[0]?.VoltageAverage ?? "0" : "0" },
                            { "DiandiParameters11", spotWelderDataList.Count > 0 ? spotWelderDataList[0]?.CurrentPeak ?? "0" : "0" },
                            { "DiandiParameters12", spotWelderDataList.Count > 0 ? spotWelderDataList[0]?.CurrentAverage ?? "0" : "0" },
                            { "DiandiParameters13", spotWelderDataList.Count > 0 ? spotWelderDataList[0]?.Power ?? "0" : "0" },
                            { "DiandiParameters14", spotWelderDataList.Count > 0 ? spotWelderDataList[0]?.Impedance ?? "0" : "0" },
                            { "DiandiParameters28", spotWelderDataList.Count > 1 ? spotWelderDataList[1]?.VoltagePeak ?? "0" : "0" },
                            { "DiandiParameters29", spotWelderDataList.Count > 1 ? spotWelderDataList[1]?.VoltageAverage ?? "0" : "0" },
                            { "DiandiParameters30", spotWelderDataList.Count > 1 ? spotWelderDataList[1]?.CurrentPeak ?? "0" : "0" },
                            { "DiandiParameters31", spotWelderDataList.Count > 1 ? spotWelderDataList[1]?.CurrentAverage ?? "0" : "0" },
                            { "DiandiParameters32", spotWelderDataList.Count > 1 ? spotWelderDataList[1]?.Power ?? "0" : "0" },
                            { "DiandiParameters33", spotWelderDataList.Count > 1 ? spotWelderDataList[1]?.Impedance ?? "0" : "0" },
                            { "DiandiParameters34", spotWelderDataList.Count > 2 ? spotWelderDataList[2]?.VoltagePeak ?? "0" : "0" },
                            { "DiandiParameters35", spotWelderDataList.Count > 2 ? spotWelderDataList[2]?.VoltageAverage ?? "0" : "0" },
                            { "DiandiParameters36", spotWelderDataList.Count > 2 ? spotWelderDataList[2]?.CurrentPeak ?? "0" : "0" },
                            { "DiandiParameters37", spotWelderDataList.Count > 2 ? spotWelderDataList[2]?.CurrentAverage ?? "0" : "0" },
                            { "DiandiParameters38", spotWelderDataList.Count > 2 ? spotWelderDataList[2]?.Power ?? "0" : "0" },
                            { "DiandiParameters39", spotWelderDataList.Count > 2 ? spotWelderDataList[2]?.Impedance ?? "0" : "0" },
                            { "DiandiParameters40", spotWelderDataList.Count > 3 ? spotWelderDataList[3]?.VoltagePeak ?? "0" : "0" },
                            { "DiandiParameters41", spotWelderDataList.Count > 3 ? spotWelderDataList[3]?.VoltageAverage ?? "0" : "0" },
                            { "DiandiParameters42", spotWelderDataList.Count > 3 ? spotWelderDataList[3]?.CurrentPeak ?? "0" : "0" },
                            { "DiandiParameters43", spotWelderDataList.Count > 3 ? spotWelderDataList[3]?.CurrentAverage ?? "0" : "0" },
                            { "DiandiParameters44", spotWelderDataList.Count > 3 ? spotWelderDataList[3]?.Power ?? "0" : "0" },
                            { "DiandiParameters45", spotWelderDataList.Count > 3 ? spotWelderDataList[3]?.Impedance ?? "0" : "0" }
                        };

                    foreach (var parameter in parameters)
                    {
                        var entityInfo = entity.GetType().GetProperty(parameter.Key, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (entityInfo != null)
                        {
                            entityInfo.SetValue(entity, Convert.ChangeType(parameter.Value, entityInfo.PropertyType), null);
                        }
                    }
                }
            }
               
         }
        #endregion

        #region 读取短路测试仪数据
        public void ProcesscircuitTester(object entity)
        {
            if(machineInfo_Type== MachineInfoTypes.短路测试仪|| machineInfo_Type == MachineInfoTypes.点底焊)
            {
                var circuitTesterDeviceList = _deviceConfig.DeviceList.Where(x => x.ServiceName == MachineInfoTypes.短路测试仪.ToString()
            && x.TaskType == TaskTypes.短路测).ToList();

                if (circuitTesterDeviceList != null && circuitTesterDeviceList.Count > 0)
                {
                    var circuitTesterDataList = new List<CircuitTesterData>();
                    foreach (var item in circuitTesterDeviceList)
                    {
                        var circuitTesteDatas = item.Communication.CircuitTesterReceive();
                        if (circuitTesteDatas != null)
                        {
                            var IR = circuitTesteDatas["IR"].Replace("\n", "");
                            var Current = circuitTesteDatas["Current"].Replace("\n", "");
                            var Voltage = circuitTesteDatas["Voltage"].Replace("\n", "");
                            var TestDatetime = DateTime.Now.ToString().Replace("\n", "");
                            circuitTesterDataList.Add(new CircuitTesterData
                            {
                                IR = IR.Length >= 5 ? IR.Substring(0, 5) : IR.PadRight(5, '0'),
                                Current = Current.Length >= 5 ? Current.Substring(0, 5) : Current.PadRight(5, '0'),
                                Voltage = Voltage.Length >= 5 ? Voltage.Substring(0, 5) : Voltage.PadRight(5, '0'),
                                TestDatetime = TestDatetime
                            });
                        }
                    }

                    var parameters = new Dictionary<string, string>
                        {
                            { "GuncaoParameters20", circuitTesterDataList.Count > 0 ? circuitTesterDataList[0]?.IR ?? "0" : "0" },
                            { "GuncaoParameters21", circuitTesterDataList.Count > 0 ? circuitTesterDataList[0]?.Voltage ?? "0" : "0" },
                            { "GuncaoParameters22", circuitTesterDataList.Count > 0 ? circuitTesterDataList[0]?.Current ?? "0" : "0" },
                            { "GuncaoParameters24", circuitTesterDataList.Count > 0 ? circuitTesterDataList[0]?.Current ?? "0" : "0" },
                            { "GuncaoParameters25", circuitTesterDataList.Count > 0 ? circuitTesterDataList[0]?.Voltage ?? "0" : "0" },

                            { "GuncaoParameters23", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                            { "GuncaoParameters29", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },



                            { "GuncaoParameters26", circuitTesterDataList.Count > 1 ? circuitTesterDataList[1]?.IR ?? "0" : "0" },
                            { "GuncaoParameters27", circuitTesterDataList.Count > 1 ? circuitTesterDataList[1]?.Voltage ?? "0" : "0" },
                            { "GuncaoParameters28", circuitTesterDataList.Count > 1 ? circuitTesterDataList[1]?.Current ?? "0" : "0" },
                            { "GuncaoParameters30", circuitTesterDataList.Count > 1 ? circuitTesterDataList[1]?.Current ?? "0" : "0" },
                            { "GuncaoParameters31", circuitTesterDataList.Count > 1 ? circuitTesterDataList[1]?.Voltage ?? "0" : "0" },


                        };

                    foreach (var parameter in parameters)
                    {
                        var entityInfo = entity.GetType().GetProperty(parameter.Key, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (entityInfo != null)
                        {
                            entityInfo.SetValue(entity, Convert.ChangeType(parameter.Value, entityInfo.PropertyType), null);
                        }
                    }

                    ////电阻
                    //data.GunCao_Parameters20 = circuitTesterDataList[0]?.IR ?? "0";
                    ////电压
                    //data.GunCao_Parameters21 = circuitTesterDataList[0]?.Voltage ?? "0";
                    ////电流
                    //data.GunCao_Parameters22 = circuitTesterDataList[0]?.Current ?? "0";
                    ////电流
                    //data.GunCao_Parameters24 = circuitTesterDataList[0]?.Current ?? "0";
                    ////电压
                    //data.GunCao_Parameters25 = circuitTesterDataList[0]?.Voltage ?? "0";

                    ////电阻2
                    //data.GunCao_Parameters26 = circuitTesterDataList[1]?.IR ?? "0";
                    ////电压2
                    //data.GunCao_Parameters27 = circuitTesterDataList[1]?.Voltage ?? "0";
                    ////电流2
                    ////电流
                    //data.GunCao_Parameters28 = circuitTesterDataList[1]?.Current ?? "0";
                    ////电流2
                    //data.GunCao_Parameters30 = circuitTesterDataList[1]?.Current ?? "0";
                    ////电压2
                    //data.GunCao_Parameters31 = circuitTesterDataList[1]?.Voltage ?? "0";


                }
            }
           
        }
        #endregion

        #region 读取白班OR夜班NG分类

        public void ProcessClassNGType(object entity, PLCBase InjMachine)
        {
            if (_mesRunParameters1 != null && _mesRunParameters2 != null)
            {
                //判断是否白班
                if (_parameter.Class.Contains("1"))
                {
                    foreach (var item in _mesRunParameters1)
                    {
                        if (!item.IsEnable) continue;
                        var valueType = GetTypeByStringHelper.GetTypeByString(item.DataType);
                        var sss = entity.GetType();
                        var entityInfo = entity.GetType().GetProperty(item.PropertyName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (entityInfo != null)
                        {
                            try
                            {
                                string value = "";
                                if (item.IsCCDResult)
                                {
                                    value = ProcessList(InjMachine.Read(item.PLCAddress, item.PLCAddressLength), 0);
                                }
                                else
                                {
                                    if (item.DataType.Contains("int32"))
                                    {
                                        var valueData = InjMachine.ReadUInt32(item.PLCAddress, 1);
                                        value = ProcessUint(valueData[0], item.DecimalNum).ToString();
                                    }
                                    else
                                    {
                                        value = ProcessList(InjMachine.Read(item.PLCAddress, item.PLCAddressLength), item.DecimalNum);
                                    }

                                }
                                //赋值
                                entityInfo.SetValue(entity, Convert.ChangeType(value, entityInfo.PropertyType), null);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }

                        }
                    }
                }
                else
                {
                    foreach (var item in _mesRunParameters2)
                    {
                        if (!item.IsEnable) continue;
                        var valueType = GetTypeByStringHelper.GetTypeByString(item.DataType);
                        var sss = entity.GetType();
                        var entityInfo = entity.GetType().GetProperty(item.PropertyName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (entityInfo != null)
                        {
                            try
                            {
                                string value = "";
                                if (item.IsCCDResult)
                                {
                                    value = ProcessList(InjMachine.Read(item.PLCAddress, item.PLCAddressLength), 0);
                                }
                                else
                                {
                                    value = ProcessList(InjMachine.Read(item.PLCAddress, item.PLCAddressLength), item.DecimalNum);
                                }
                                //赋值
                                entityInfo.SetValue(entity, Convert.ChangeType(value, entityInfo.PropertyType), null);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }

                        }
                    }
                }



            }
        }
        #endregion
    }
}
